package com.qianfeng.openapi.web.master.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qianfeng.openapi.web.master.dto.TableData;
import com.qianfeng.openapi.web.master.entity.ApiMapping;
import com.qianfeng.openapi.web.master.feign.CacheServiceClient;
import com.qianfeng.openapi.web.master.mapper.ApiMappingMapper;
import com.qianfeng.openapi.web.master.service.ApiMappingService;
import com.qianfeng.openapi.web.master.utils.SysConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/12/30
 * @Time: 下午10:43
 */
@Service
@Transactional
public class ApiMappingServiceImpl implements ApiMappingService {

    @Resource
    private ApiMappingMapper apiMappingMapper;

    @Resource
    private CacheServiceClient cacheServiceClient;

    private Logger logger = LoggerFactory.getLogger(ApiMappingServiceImpl.class);


    @Override
    public TableData apiMappingTableList(
            String gatewayApiName, Integer state,
            int offset, int limit) {
        //IPage<T> page, @Param("ew") Wrapper<T> queryWrapper
        IPage iPage = new Page();
        //(nowPage-1)*pageSize = offset
        int current = offset/limit+1;
        iPage.setCurrent(current);
        iPage.setSize(limit);
        ((Page) iPage).setSearchCount(true);

        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(gatewayApiName)){
            queryWrapper.like("gateway_api_name",
                    gatewayApiName);
        }
        if (state!=null){
            queryWrapper.like("state",
                    state);
        }


        iPage = apiMappingMapper.selectPage(iPage,queryWrapper);

        TableData data = new TableData();
        data.setRows(iPage.getRecords());
        data.setTotal(iPage.getTotal());
        return data;
    }

    @Override
    public R addApiMapping(ApiMapping apiMapping) {
        int  i = apiMappingMapper.insert(apiMapping);
        if (i>0){
            logger.info("新增--->同步缓存");
            //String set list hash zset
            //  apiMapping 转成json  存储String  key  value
            //    hash   key  field  value
            Map map = new HashMap();
            //必须   网关动态路由
            map.put("serviceId",apiMapping.getServiceId());
            map.put("requestURL",apiMapping.getInsideApiUrl());
            //可选
            map.put("description",apiMapping.getDescription());
            map.put("gatewayApiName",apiMapping.getGatewayApiName());
            map.put("id",apiMapping.getId()+"");
            map.put("state",apiMapping.getState()+"");

            //api_mapping_jingdong.product.info
            cacheServiceClient.hmset(SysConstant.API_MAPPING+
                    apiMapping.getGatewayApiName(),map);
        }

        return i>0?R.ok(null):R.failed("新增失败");
    }


    @Override
    public R batchDelete(List<Integer> id) {
        List<ApiMapping> list  = apiMappingMapper.selectBatchIds(id);


        int  i = apiMappingMapper.deleteBatchIds(id);

        if (i>0){

            for (ApiMapping apiMapping : list) {
                logger.info("{同步删除缓存：}"+apiMapping.getGatewayApiName());
                cacheServiceClient.delKey(SysConstant.API_MAPPING+apiMapping.getGatewayApiName());
            }

        }

        return i>0?R.ok(null):R.failed("删除失败");
    }

    @Override
    public R apiMappingInfo(int id) {
        ApiMapping apiMapping = apiMappingMapper.selectById(id);

        return R.ok(apiMapping);
    }

    @Override
    public R updateApiMapping(ApiMapping apiMapping) {
        //1.先得到老数据
        ApiMapping old = apiMappingMapper.selectById(apiMapping.getId());
        //2.再更新数据库
        int i = apiMappingMapper.updateById(apiMapping);

        if(i>0){
            //3.清除缓存中老数据
             cacheServiceClient.delKey(SysConstant.API_MAPPING+old.getGatewayApiName());

             //4.更新后的新数据同步到缓存中
            Map map = new HashMap();
            //必须   网关动态路由
            map.put("serviceId",apiMapping.getServiceId());
            map.put("requestURL",apiMapping.getInsideApiUrl());
            //可选
            map.put("description",apiMapping.getDescription());
            map.put("gatewayApiName",apiMapping.getGatewayApiName());
            map.put("id",apiMapping.getId()+"");
            map.put("state",apiMapping.getState()+"");

            cacheServiceClient.hmset(SysConstant.API_MAPPING+apiMapping.getGatewayApiName(),map);
        }

        return i>0?R.ok(null):R.failed("修改失败");
    }
}
